package ezXpns;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;


//@author A0088827L
public class TypeRegistry implements Iterable<String> {	
	public static class Serializer implements JsonSerializer<TypeRegistry> {
		@Override
		public JsonElement serialize(TypeRegistry registry, Type type,
				JsonSerializationContext ctx) {
			return ctx.serialize(registry.types);
		}
	}
	
	public static class Deserializer implements JsonDeserializer<TypeRegistry> {
		@Override
		public TypeRegistry deserialize(JsonElement json, Type type,
				JsonDeserializationContext ctx) throws JsonParseException {
			TypeRegistry registry = new TypeRegistry();
			
			for(JsonElement element: json.getAsJsonArray()) {
				registry.types.add(element.getAsString());
			}
			
			return registry;
		}		
	}
	
	public boolean addType(String type) {
		if(!types.contains(type)) {
			types.add(type);
			return true;
		}
		else
			return false;
	}
	
	public void removeType(String type) {
		if(types.contains(type)) {
			types.remove(type);
		}
	}
	
	public boolean renameType(String oldName, String newName) {
		if(types.contains(oldName) && !types.contains(newName)) {
			types.remove(oldName);
			types.add(newName);
			return true;
		}
		else
			return false;
	}
	
	public boolean hasType(String type) {
		return types.contains(type);
	}
	
	@Override
	public Iterator<String> iterator() {
		return types.iterator();
	}
	
	private Collection<String> types = new ArrayList<String>();
}
